package com.flyme.module.base.provider.api;


import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.flyme.common.core.constants.CommonConstants;
import com.flyme.common.core.model.ResultBody;
import com.flyme.common.core.model.query.CriteriaQuery;
import com.flyme.common.core.model.query.PagerInfo;
import com.flyme.common.core.model.query.PqGrid;
import com.flyme.common.core.security.OpenHelper;
import com.flyme.common.core.security.OpenUserAuth;
import com.flyme.common.core.utils.*;
import com.flyme.core.base.supper.controller.BaseController;
import com.flyme.core.base.supper.entity.EntityMap;
import com.flyme.module.base.client.constants.BaseConstants;
import com.flyme.module.base.client.dto.SysThirdLogin;
import com.flyme.module.base.client.entity.*;
import com.flyme.module.base.client.enums.*;
import com.flyme.module.base.provider.aliyunren.VerifyMaterial;
import com.flyme.module.base.provider.service.*;
import com.flyme.module.order.client.entity.OrderInfo;
import com.flyme.module.order.client.entity.PayBeforeHandler;
import com.flyme.module.order.client.enums.OrderTypeEnum;
import com.flyme.module.order.provider.service.OrderService;
import com.google.common.collect.Maps;
import com.google.zxing.EncodeHintType;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.nio.charset.Charset;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @author flyme
 */
@Slf4j
@Api(tags = "app个人中心接口")
@RestController
@RequestMapping("/user")
public class ApiUserController extends BaseController<SysUserService, SysUser> {

    @Autowired
    private SysAccountService accountService;
    @Autowired
    private SysWorkCourseService workCourseService;
    @Autowired
    private SysConfigService configService;
    @Autowired
    private SysEducationService educationService;
    @Autowired
    private SysVipService vipService;
    @Autowired
    private SysColleconService colleconService;
    @Autowired
    private SysHistoryService historyService;
    @Autowired
    private SysPlanrecordService planrecordService;
    @Autowired
    private SysFeedbackService feedbackService;
    @Autowired
    private SysUsercertificateService sysUsercertificateService;
    @Autowired
    private SysGkregisterService sysGkregisterService;
    @Autowired
    private SysUserEduationService sysUserEduationService;
    @Autowired
    private SysUserTrainService sysUserTrainService;
    @Autowired
    private SysUserWorkService sysUserWorkService;
    @Autowired
    private SysUserexaminationService sysUserexaminationService;
    @Autowired
    private SysExaminationService sysExaminationService;
    @Autowired
    private SysConditionitemService sysConditionitemService;
    @Autowired
    private SysCertificateService sysCertificateService;
    @Autowired
    private SysExamtypeService sysExamtypeService;
    @Autowired
    private SysExamseasonService sysExamseasonService;
    @Autowired
    private ObjectMapper objectMapper;
    @Resource
    private AutowireCapableBeanFactory spring;
    @Autowired
    private SysExatimeService sysExatimeService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private SysenumService sysenumService;
    @Autowired
    private SysConfigService sysConfigService;


    /**
     * 获取openid
     *
     * @return
     */
    @RequestMapping(value = "/getOpenId")
    public ResultBody getOpenId(@RequestParam(value = "accessToken") String accessToken) {
        Map<String, String> map = Maps.newHashMap();
        String url = CommonConstants.OPEN_URL + "appid=" + CommonConstants.APPID + "&secret=" + CommonConstants.SECRET + "&js_code=" + accessToken
                + "&grant_type=authorization_code";
        try {
            String jsonstr = HttpUtil.get(url, Charset.defaultCharset());
            Map<String, Object> objectMap = JsonUtils.json2mapDeeply(jsonstr);
            return ResultBody.success(objectMap.get("openid").toString());
        } catch (Exception e) {
            e.printStackTrace();
            return ResultBody.failed("网络请求失败");
        }
    }

    /**
     * 用户基本资料(缺公司名称)
     */
    @RequestMapping(value = "/info")
    public ResultBody info() {
        OpenUserAuth userAuth = OpenHelper.getUserAuth();
        String loginType = userAuth.getLoginType();
        EntityMap user = bizService.getEntityMap(q().eq("id", userAuth.getUserId()));
        String avatar = user.get("avatar");
        String nickName = user.get("nickName");
        if (ObjectUtils.isEmpty(avatar) || BaseConstants.DEFAULT_USERHEAD.equals(avatar)) {
            if (!BaseConstants.USER_ACCOUNT_TYPE_MOBILE.equals(loginType)) {
                user.put("avatar", userAuth.getAvatar());
            }
        }
        if (ObjectUtils.isEmpty(nickName)) {
            if (!BaseConstants.USER_ACCOUNT_TYPE_MOBILE.equals(loginType)) {
                user.put("nickName", userAuth.getNickName());
            }
        }

        EntityMap vip = vipService.getVipByUser(userAuth.getUserId());
        user.put("vipName", "");
        user.put("vipExpiryDate", "");
        user.put("isVip", 0);
        user.put("vipCode", "");
        //isVip:0非vip，1vip，2vip已过期
        if (ObjectUtils.isNotEmpty(vip)) {
            user.put("vipName", "VIP会员");
            user.put("vipExpiryDate", vip.get("expiryDate").toString().substring(0, 10));
            user.put("isVip", 2);
            user.put("vipCode", vip.get("vipCode"));
            //判断是否已过期，
            Long a = DateUtil.between(DateUtil.date(), DateUtil.parseDateTime(vip.get("expiryDate").toString()), DateUnit.MINUTE, false);
            if (a > 0) {//未过期
                user.put("isVip", 1);
            }
        }
        return ResultBody.success(user);
    }

    /**
     * 我的页面
     */
    @RequestMapping(value = "/mine")
    public ResultBody myCentre() {
        OpenUserAuth userAuth = OpenHelper.getUserAuth();
        String loginType = userAuth.getLoginType();
        EntityMap user = bizService.getEntityMap(q().eq("id", userAuth.getUserId()));
        String avatar = user.get("avatar");
        String nickName = user.get("nickName");
        if (ObjectUtils.isEmpty(avatar) || BaseConstants.DEFAULT_USERHEAD.equals(avatar)) {
            if (!BaseConstants.USER_ACCOUNT_TYPE_MOBILE.equals(loginType)) {
                user.put("avatar", userAuth.getAvatar());
            }
        }
        if (ObjectUtils.isEmpty(nickName)) {
            if (!BaseConstants.USER_ACCOUNT_TYPE_MOBILE.equals(loginType)) {
                user.put("nickName", userAuth.getNickName());
            }
        }
        EntityMap vip = vipService.getVipByUser(userAuth.getUserId());
        user.put("vipName", "");
        user.put("vipExpiryDate", "");
        user.put("isVip", 0);
        user.put("vipCode", "");
        //isVip:0非vip，1vip，2vip已过期
        if (ObjectUtils.isNotEmpty(vip)) {
            user.put("vipName", "VIP会员");
            user.put("vipExpiryDate", vip.get("expiryDate").toString().substring(0, 10));
            user.put("isVip", 2);
            user.put("vipCode", vip.get("vipCode"));
            //判断是否已过期
            Long a = DateUtil.between(DateUtil.date(), DateUtil.parseDateTime(vip.get("expiryDate").toString()), DateUnit.MINUTE, false);
            if (a > 0) {//未过期
                user.put("isVip", 1);
            }
        }
        Integer planNum = planrecordService.countByUser(userAuth.getUserId());
        Integer leaveMessNum = feedbackService.countByUser(userAuth.getUserId());
        SysConfig sysconfig = configService.getByName("SERVICEPHONE");
        user.put("servicePhone", sysconfig.getConfigVal());
        user.put("planNum", planNum);
        user.put("leaveMessNum", leaveMessNum);
        return ResultBody.success(user);
    }

    /**
     * 更新用户基本资料
     */
    @RequestMapping(value = "/update")
    public ResultBody update(SysUser user) {
        OpenUserAuth userAuth = OpenHelper.getUserAuth();
        String email = user.getEmail();
        if (ObjectUtils.isNotEmpty(email)) {
            if (!StringUtils.matchEmail(email)) {
                return ResultBody.failed("邮箱格式不正确");
            }
        }
        user.setId(userAuth.getUserId());
        bizService.saveOrUpdate(user);
        return ResultBody.ok("更新成功");
    }

    /**
     * 更新用户基本资料
     */
    @RequestMapping(value = "/updateUserInfo")
    public ResultBody updateUserInfo(SysUser user) {
        OpenUserAuth userAuth = OpenHelper.getUserAuth();
        String email = user.getEmail();
        if (ObjectUtils.isNotEmpty(email)) {
            if (!StringUtils.matchEmail(email)) {
                return ResultBody.failed("邮箱格式不正确");
            }
        }
        user.setId(userAuth.getUserId());
        bizService.saveOrUpdate(user);
        return ResultBody.ok("更新成功");
    }

    /**
     * 身份审核
     */
    @RequestMapping(value = "/saveidentity")
    public ResultBody saveidentity(String idCard, String cardNoImg, String cardNoImg2, String imagePath) {
        OpenUserAuth userAuth = OpenHelper.getUserAuth();
        if (ObjectUtils.isEmpty(userAuth.getUserId())) {
            return ResultBody.failed("请重新登陆");
        }
        if (ObjectUtils.isEmpty(idCard) || ObjectUtils.isEmpty(cardNoImg) || ObjectUtils.isEmpty(cardNoImg2) || ObjectUtils.isEmpty(imagePath)) {
            return ResultBody.failed("参数不完整");
        }
        SysUser user = bizService.getById(userAuth.getUserId());
        if (ObjectUtils.isEmpty(user)) {
            return ResultBody.failed("用户不存在");
        }
        QueryWrapper<SysUser> qw = new QueryWrapper();
        qw.eq("idCard", idCard);
        List<SysUser> userlist = bizService.list(qw);
        if (ObjectUtils.isNotEmpty(userlist) && !userlist.get(0).getId().equals(userAuth.getUserId())) {
            return ResultBody.failed("该身份证号已认证其他账户");
        }
        user.setIdCard(idCard);
        user.setCardLiveImg(imagePath);
        user.setCardNoImg(cardNoImg);
        user.setCardNoImg2(cardNoImg2);
        user.setId(userAuth.getUserId());
        bizService.saveOrUpdate(user);
        return ResultBody.ok("操作成功");
    }


    /**
     * 初始化国开申请页面
     */
    @RequestMapping(value = "/initgkaccount")
    public ResultBody initgkaccount() {
        OpenUserAuth userAuth = OpenHelper.getUserAuth();
        EntityMap map = new EntityMap();
        ResultBody resultBody = new ResultBody();
        if (ObjectUtils.isEmpty(userAuth.getUserId())) {
            return ResultBody.failed("请重新登陆");
        }
        SysUser user = bizService.getById(userAuth.getUserId());
        QueryWrapper<SysGkregister> qw = new QueryWrapper();
        qw.eq("idCard", user.getIdCard());
        SysGkregister sysGkregister = sysGkregisterService.getOne(qw);
        if (ObjectUtils.isNotEmpty(sysGkregister)) {
            map.put("sysGkregister", sysGkregister);
        } else {
            map.put("sysGkregister", "");
        }
        resultBody.setData(map);
        return resultBody;
    }


    /**
     * 提交国开学籍注册
     *
     * @param sysGkregister
     * @return
     */
    @RequestMapping(value = "/savegkaccount")
    public ResultBody savegkaccount(SysGkregister sysGkregister) {
        ResultBody resultBody = new ResultBody();
        Boolean a = false;
        if (ObjectUtils.isNotEmpty(sysGkregister.getId())) {
            a = sysGkregisterService.updateById(sysGkregister);
        } else {
            a = sysGkregisterService.save(sysGkregister);
        }
        if (a) {
            resultBody.setInfo("提交成功");
        } else {
            resultBody.setInfo("提交失败");
        }
        return resultBody;

    }

    /**
     * 我的考试
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/myExamination")
    public ResultBody myExamination(PagerInfo pagerInfo, int page, int limit, String examStatus, Long examTypeId) {
        pagerInfo.setPageNumber(page);
        pagerInfo.setPageSize(limit);
        EntityMap map = new EntityMap();
        OpenUserAuth userAuth = OpenHelper.getUserAuth();
        CriteriaQuery<SysUserexamination> qw = new CriteriaQuery(pagerInfo);
        qw.select("u.*,exam.examName,exam.remark,exam.exanMode,exam.examTime,exam.examEndTime,exam.examinationHtml,orderinfo.id as orderId");
        qw.notIn("u.examStatus", 3);
        if(ObjectUtils.isNotEmpty(examStatus)){
            qw.eq("u.examStatus", examStatus);
        }
        if(ObjectUtils.isNotEmpty(examTypeId)){
            qw.eq("exam.examTypeId", examTypeId);
        }
        qw.createAlias("exam", "exam");
        qw.createAlias("orderinfo", "orderinfo");
        qw.eq("u.userId", userAuth.getUserId());
        qw.orderByDesc("u.createTime");
        PqGrid pageList = sysUserexaminationService.pageList(qw);
        List<EntityMap> list = pageList.getRows();
        for (EntityMap map_val : list) {
            String exatimeId = map_val.get("exatimeId");
            List<EntityMap> seasonList = new ArrayList<>();
            if (exatimeId.contains(",")) {
                String[] exatimeIds = exatimeId.split(",");
                for (String s : exatimeIds) {
                    SysExatime b = sysExatimeService.getById(Long.parseLong(s));
                    SysExamseason a = sysExamseasonService.getById((b.getExamseasonId()));
                    EntityMap seasonMap = new EntityMap();
                    seasonMap.put("childexamName", a.getChildexamName());
                    seasonMap.put("examStartTime", b.getExamStartTime());
                    seasonMap.put("examEndTime", b.getExamendTime());
                    seasonMap.put("examTime", b.getExamTime());
                    seasonList.add(seasonMap);
                }
            } else {
                SysExatime b = sysExatimeService.getById(Long.parseLong(exatimeId));
                SysExamseason a = sysExamseasonService.getById(b.getExamseasonId());
                EntityMap seasonMap = new EntityMap();
                seasonMap.put("childexamName", a.getChildexamName());
                seasonMap.put("examStartTime", b.getExamStartTime());
                seasonMap.put("examEndTime", b.getExamendTime());
                seasonMap.put("examTime", b.getExamTime());
                seasonList.add(seasonMap);
            }
            map_val.put("seasonList", seasonList);
        }

        return ResultBody.success(pageList);
    }

    /**
     * 人脸识别接口（小程序pc）
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/identiybody")
    public ResultBody identiybody(String imagePath, String idCardNum, String name, String identityflg) {
        EntityMap map = new EntityMap();
        OpenUserAuth userAuth = OpenHelper.getUserAuth();
        VerifyMaterial verifyMaterial = new VerifyMaterial();
        SysUser user = bizService.getById(userAuth.getUserId());
        user.setCardLiveImg(imagePath);
        bizService.saveOrUpdate(user);

        String returnStr = verifyMaterial.verifyMaterial(imagePath, "signexam", UUID.randomUUID().toString(), name, idCardNum);
        if(ObjectUtils.isEmpty(returnStr)){
            return ResultBody.failed("认证失败，请重新认证");
        }
        try {
            ObjectMapper mapper = new ObjectMapper();
            Map<String, Object> return_str = JsonUtils.json2MapRecursion(returnStr, objectMapper);
            if (return_str.get("verifyStatus").equals(1)) {
                if (ObjectUtils.isNotEmpty(identityflg)) {
                    user.setLicenseStatus("1");
                    user.setUserName(name);
                    bizService.saveOrUpdate(user);
                }
                return ResultBody.success("认证成功");
            } else {
                if (ObjectUtils.isNotEmpty(identityflg)) {
                    user.setLicenseStatus("2");
                    bizService.saveOrUpdate(user);
                }
                return ResultBody.failed("认证失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 人脸识别成功后调用（更新用户正面照）
     */
    @RequestMapping(value = "/editUserLive")
    public ResultBody editUserLive(String imagePath, String cardNoImg, String cardNoImg2) {
        OpenUserAuth userAuth = OpenHelper.getUserAuth();
        SysUser user = bizService.getById(userAuth.getUserId());
        user.setCardLiveImg(imagePath);
        user.setCardNoImg(cardNoImg);
        user.setCardNoImg2(cardNoImg2);
        Boolean flag = bizService.saveOrUpdate(user);
        return ResultBody.success(flag);
    }

    /**
     * 人脸识别接口
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/getverifyToken")
    public ResultBody getverifyToken(String FaceRetainedImageUrl) {
        VerifyMaterial verifyMaterial = new VerifyMaterial();
        String returnStr = verifyMaterial.describeVerifyToken(FaceRetainedImageUrl, "FVUse", UUID.randomUUID().toString());
        EntityMap resultmap = new EntityMap();
        try {
            Map<String, Object> map = JsonUtils.json2mapDeeply(returnStr);
            resultmap.put("verifyToken", map.get("verifyToken"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultBody.success(resultmap);
    }

    /**
     * 人脸识别回调状态接口
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/verifyupdateuser")
    public ResultBody verifyupdateuser(String verifyStatus, String userName) {
        OpenUserAuth userAuth = OpenHelper.getUserAuth();
        SysUser user = bizService.getById(userAuth.getUserId());
        if (ObjectUtils.isNotEmpty(user)) {
            if (ObjectUtils.isEmpty(user.getLicenseStatus()) || !user.getLicenseStatus().equals("1")) {
                user.setUserName(userName);
                user.setLicenseStatus(verifyStatus);
                bizService.saveOrUpdate(user);
            }
        }
        return ResultBody.success(user);
    }


    /**
     * 我的个人资料
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/userInfo")
    public ResultBody myMinemessage() {
        EntityMap map = new EntityMap();
        OpenUserAuth userAuth = OpenHelper.getUserAuth();
        EntityMap user = bizService.findByUserId(userAuth.getUserId());
        if (ObjectUtils.isEmpty(user.get("idCard")) || ObjectUtils.isEmpty(user.get("cardNoImg")) || ObjectUtils.isEmpty(user.get("cardNoImg2"))) {
            map.put("identityTag", 0);
        } else {
            map.put("identityTag", 1);
        }
        map.put("userInfo", user);
        //教育信息是否填写
        List<SysUserEduation> eduationList = sysUserEduationService.selectByUserId(userAuth.getUserId());
        if (ObjectUtils.isNotEmpty(eduationList) && eduationList.size() > 0) {
            map.put("edutionTag", 1);
        } else {
            map.put("edutionTag", 0);
        }
        List<SysUsercertificate> certificates = sysUsercertificateService.selectByUserId(userAuth.getUserId());

        if (ObjectUtils.isNotEmpty(certificates) && certificates.size() > 0) {
            map.put("certificatesCount", certificates.size());
        } else {
            map.put("certificatesCount", 0);
        }
        //工作经历是否填写
        List<SysUserWork> workList = sysUserWorkService.selectByUserId(userAuth.getUserId());
        if (ObjectUtils.isNotEmpty(workList) && workList.size() > 0) {
            map.put("workTag", 1);
        } else {
            map.put("workTag", 0);
        }
        //培训经历是否填写
        List<SysUserTrain> trainList = sysUserTrainService.selectByUserId(userAuth.getUserId());
        if (ObjectUtils.isNotEmpty(trainList) && trainList.size() > 0) {
            map.put("trainTag", 1);
        } else {
            map.put("trainTag", 0);
        }
        return ResultBody.success(map);
    }


    /**
     * 工作经历页面
     */
    @RequestMapping(value = "/workcourse_list")
    public ResultBody workcourseList() {
        OpenUserAuth userAuth = OpenHelper.getUserAuth();
        EntityMap map = new EntityMap();
        List<SysWorkCourse> list = workCourseService.selectByUserId(userAuth.getUserId());
        List<EntityMap> commercials = CommercialEnum.getList();
        List<EntityMap> posts = PostEnum.getList();
        List<EntityMap> workingYears = WorkingYearEnum.getList2();
        map.put("list", list);
        map.put("commercials", commercials);//业态
        map.put("posts", posts);//职位
        map.put("workingYears", workingYears);//工作年限
        return ResultBody.success(map);
    }

    /**
     * 新增工作经历页面
     */
    @RequestMapping(value = "/workcourse_add")
    public ResultBody workcourseAdd() {
        EntityMap map = new EntityMap();
        List<EntityMap> commercials = CommercialEnum.getList();
        List<EntityMap> posts = PostEnum.getList();
        List<EntityMap> workingYears = WorkingYearEnum.getList();
        map.put("commercials", commercials);//业态
        map.put("posts", posts);//职位
        map.put("workingYears", workingYears);//工作年限
        return ResultBody.success(map);
    }

    /**
     * 提交_工作经历
     */
    @RequestMapping(value = "/workcourse_sub")
    public ResultBody addWork(SysWorkCourse workcourse) {
        if (ObjectUtils.isNotEmpty(workcourse.getIsWork()) && workcourse.getIsWork().equals(1)) {
            return ResultBody.failed("该工作经历已认证，无法修改");
        }
        OpenUserAuth userAuth = OpenHelper.getUserAuth();
        workcourse.setUserId(userAuth.getUserId());
        workcourse.setIsWork(1);
        Boolean tag = workCourseService.saveOrUpdate(workcourse);
        /*if (tag) {
            gradeWork(workcourse);
        }*/
        return ResultBody.success(tag);
    }


    /**
     * 删除工作经历
     */
    @RequestMapping(value = "/workcourse_del")
    public ResultBody workcourse_del(String id) {
        ApiAssert.notNull("参数不能为空", id);
        boolean tag = workCourseService.removeById(id);
        return ResultBody.success(tag);
    }

    /**
     * 工作经历删除
     */
    @RequestMapping(value = "/delwork")
    public ResultBody delwork(Long workId) {
        OpenUserAuth userAuth = OpenHelper.getUserAuth();
        EntityMap map = new EntityMap();
        SysUserWork work = sysUserWorkService.getById(workId);
        if (ObjectUtils.isEmpty(work)) {
            return ResultBody.failed("该工作经历不存在");
        }
        boolean a = sysUserWorkService.removeById(workId);
        if (a) {
            return ResultBody.success("删除成功");
        }
        return ResultBody.failed("提交失败");
    }

    /**
     * 培训经历删除
     */
    @RequestMapping(value = "/delTrain")
    public ResultBody delTrain(Long trainId) {
        OpenUserAuth userAuth = OpenHelper.getUserAuth();
        EntityMap map = new EntityMap();
        SysUserTrain train = sysUserTrainService.getById(trainId);
        if (ObjectUtils.isEmpty(train)) {
            return ResultBody.failed("该培训经历不存在");
        }
        boolean a = sysUserTrainService.removeById(trainId);
        if (a) {
            return ResultBody.success("删除成功");
        }
        return ResultBody.failed("提交失败");
    }

    /**
     * 教育经历删除
     */
    @RequestMapping(value = "/delEduation")
    public ResultBody delEduation(Long eduationId) {
        OpenUserAuth userAuth = OpenHelper.getUserAuth();
        EntityMap map = new EntityMap();
        SysUserEduation eduation = sysUserEduationService.getById(eduationId);
        if (ObjectUtils.isEmpty(eduation)) {
            return ResultBody.failed("该教育经历不存在");
        }
        boolean a = sysUserEduationService.removeById(eduationId);
        if (a) {
            return ResultBody.success("删除成功");
        }
        return ResultBody.failed("提交失败");
    }

    /**
     * 教育经历
     */
    @PostMapping(value = "/education_list")
    public ResultBody educationPage(@RequestParam(value = "test", required = false) String test) {
        OpenUserAuth userAuth = OpenHelper.getUserAuth();
        CriteriaQuery cq = new CriteriaQuery();
        EntityMap education = educationService.getEntityMap(cq.eq("userId", userAuth.getUserId()));
        Map<String, Object> map = new HashMap<String, Object>();
        List<EntityMap> educationList = EducationEnum.getList();
        List<EntityMap> professionList = ProfessionEnum.getList();
        List<EntityMap> rankList = RankEnum.getList();
        map.put("education", education);
        map.put("educationList", educationList);//学历分类
        map.put("professionList", professionList);//专业分类
        map.put("rankList", rankList);//级别分类
        return ResultBody.success(map);
    }

    /**
     * 修改用户教育经历
     */
    @RequestMapping(value = "/updateEducation")
    public ResultBody updateEducation(SysEducation education) {
        ApiAssert.notNull("参数不能为空", education.getSchoolName(), education.getEducation(), education.getMajor());
        if (ObjectUtils.isNotEmpty(education.getIsEducation()) && education.getIsEducation().equals(1)) {
            return ResultBody.failed("该教育经历已认证，无法修改");
        }
        OpenUserAuth userAuth = OpenHelper.getUserAuth();
        education.setUserId(userAuth.getUserId());
        education.setIsEducation(1);
        Boolean tag = educationService.saveOrUpdate(education);
        //gradeEducation(education);
        return ResultBody.success(tag);
    }

    /**
     * 账号管理页面
     */
    @RequestMapping(value = "/bind_list")
    public ResultBody bindList() {
        OpenUserAuth userAuth = OpenHelper.getUserAuth();
        EntityMap map = new EntityMap();
        SystemAccount qq = accountService.get(userAuth.getUserId(), BaseConstants.USER_ACCOUNT_TYPE_QQ);
        SystemAccount weibo = accountService.get(userAuth.getUserId(), BaseConstants.USER_ACCOUNT_TYPE_WEIBO);
        SystemAccount weixin = accountService.get(userAuth.getUserId(), BaseConstants.USER_ACCOUNT_TYPE_WEIXIN);
        Long qqId = 0L;
        Long weiboId = 0L;
        Long weixinId = 0L;
        if (ObjectUtils.isNotEmpty(qq)) {
            qqId = qq.getId();
        }
        if (ObjectUtils.isNotEmpty(weibo)) {
            weiboId = weibo.getId();
        }
        if (ObjectUtils.isNotEmpty(weixin)) {
            weixinId = weixin.getId();
        }
        map.put("Weixin", weixinId);
        map.put("QQ", qqId);
        map.put("Weibo", weiboId);
        return ResultBody.success(map);
    }

    /**
     * 解绑第三方账户
     */
    @RequestMapping(value = "/bind_del")
    public ResultBody bindDel(String id) {
        ApiAssert.notNull("参数不能为空", id);
        boolean tag = accountService.removeById(id);
        return ResultBody.success("解绑成功", tag);
    }

    /**
     * 綁定第三方账户
     */
    @RequestMapping(value = "/bind_add")
    public ResultBody bindDel(SysThirdLogin thirdLogin) {
        OpenUserAuth userAuth = OpenHelper.getUserAuth();
        thirdLogin.setUserId(userAuth.getUserId());
        Boolean isBind = accountService.bind(thirdLogin);
        EntityMap map = new EntityMap();
        Boolean qq = accountService.isExist(userAuth.getUserId(), BaseConstants.USER_ACCOUNT_TYPE_QQ);
        Boolean weibo = accountService.isExist(userAuth.getUserId(), BaseConstants.USER_ACCOUNT_TYPE_WEIBO);
        Boolean weixin = accountService.isExist(userAuth.getUserId(), BaseConstants.USER_ACCOUNT_TYPE_WEIXIN);
        map.put("Weixin", weixin);
        map.put("QQ", qq);
        map.put("Weibo", weibo);
        if (isBind) {
            return ResultBody.success("绑定成功", map);
        } else {
            return ResultBody.failed("已绑定其他账户", map);
        }

    }

    /**
     * 我的收藏
     */
    @RequestMapping(value = "/collecon_mine")
    public ResultBody userCollecon(@ModelAttribute(value = "pagerInfo") PagerInfo pagerInfo) {
        OpenUserAuth userAuth = OpenHelper.getUserAuth();
        CriteriaQuery cq = new CriteriaQuery<SysCollecon>(pagerInfo);
        cq.select("c.targetType,c.id colleconId,cs.recordNum,c.targetId,cs.isFree,cs.isVipFree,cs.onLine,"
                + "CASE WHEN ISNULL(cs.courseImage) THEN live.liveImage ELSE cs.courseImage END img,"
                + "CASE WHEN ISNULL(cs.courseTitle) THEN live.liveTitle ELSE cs.courseTitle END title,"
                + "(select count(id) from sys_catalog ca where ca.courseId=c.targetId and parentId!=0) cataNum,"
                //+ "CASE WHEN ISNULL(cs.courseCount) THEN 0 ELSE cs.courseCount END cataNum,"
                + "CASE WHEN ISNULL(l.lecturerName) THEN le.lecturerName ELSE l.lecturerName END lecturerName");
        cq.eq("userId", userAuth.getUserId());
        cq.eq("optType", 1);
        cq.orderByDesc("c.createTime");
        cq.createAlias("course", "cs");
        cq.createAlias("lecturer", "l");
        cq.createAlias("live", "live");
        cq.createAlias("lecturer2", "le");
        PqGrid pqGrid = colleconService.pageList(cq);
        return ResultBody.success(pqGrid);
    }

    /**
     * 删除浏览记录
     */
    @RequestMapping(value = "/history_del")
    public ResultBody delHistory(HttpServletResponse response, String historyId) {
        ApiAssert.notNull("参数不能为空", historyId);
        boolean flag = historyService.removeById(historyId);
        return ResultBody.success("删除成功", flag);
    }

    /**
     * 删除所有浏览记录
     */
    @RequestMapping(value = "/history_delAll")
    public ResultBody delHistoryAll(HttpServletResponse response) {
        OpenUserAuth userAuth = OpenHelper.getUserAuth();
        boolean flag = historyService.removeAll(userAuth.getUserId());
        return ResultBody.success("删除成功", flag);
    }

    /**
     * 记录页面
     */
    @RequestMapping(value = "/recordList")
    public ResultBody recordList(@ModelAttribute(value = "pagerInfo") PagerInfo pagerInfo) {
        OpenUserAuth userAuth = OpenHelper.getUserAuth();
        EntityMap map = bizService.getEntityMap(q().eq("id", userAuth.getUserId()));
        SysVipType vipType = vipService.getUserVip(userAuth.getUserId());
        map.put("vipName", "");
        if (ObjectUtils.isNotEmpty(vipType)) {
            map.put("vipName", vipType.getVipName());
        }
        //浏览记录
        CriteriaQuery cq = new CriteriaQuery<EntityMap>(pagerInfo);
        cq.select("h.id historyId,c.isVipFree,c.courseImage,c.recordNum,c.isFree,c.coursePrice,c.courseTitle,c.id courseId," +
                "(select count(id) from sys_catalog ca where ca.courseId=c.id and parentId!=0) cataNum,l.lecturerName");
        cq.eq("h.userId", userAuth.getUserId());
        cq.orderByDesc("h.updateTime");
        cq.createAlias("course", "c");
        cq.createAlias("lecturer", "l");
        PqGrid pqGrid = historyService.pageList(cq);
        map.put("history", pqGrid.getRows());
        return ResultBody.success(map);
    }

    /**
     * 考试报名（验证报考条件）
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/addsubjects")
    public ResultBody addsubjects(@RequestParam(value = "examId", required = false) String examId, @RequestParam(value = "seasonId", required = false) String seasonId) {
        EntityMap map = new EntityMap();
        OpenUserAuth userAuth = OpenHelper.getUserAuth();
        CriteriaQuery<SysUser> qw = new CriteriaQuery();
        qw.eq("id", userAuth.getUserId());
        SysUser user = bizService.getOne(qw);

        //校验用户是否参加过该考试时
        EntityMap isApply = sysUserexaminationService.checkByUser(user.getId(), Long.parseLong(examId));
        if(isApply.get("isApply").equals("1")){
            if(isApply.get("addExa").equals("0")){
                return ResultBody.failed("您有该考试待支付订单", isApply.get("orderId")).setCode(105);
            }else{
                return ResultBody.failed("该考试您已报名");
            }
        }
        if (ObjectUtils.isEmpty(user.getIdCard()) || ObjectUtils.isEmpty(user.getCardNoImg()) || ObjectUtils.isEmpty(user.getCardNoImg2())) {
            return ResultBody.failed("信息不完整，请先完善个人资料");
        }
        //教育信息是否填写
        List<Integer> edaution_result = new ArrayList<>();
        List<SysUserEduation> eduationList = sysUserEduationService.selectLeavelByUserId(userAuth.getUserId());
        if (ObjectUtils.isEmpty(eduationList)) {
            return ResultBody.failed("信息不完整，请先完善个人教育资料");
        } else {
            for (SysUserEduation eduation : eduationList) {
                edaution_result.add(Integer.parseInt(eduation.getQualifiLeavel()));
            }
        }
        //工作经历是否填写
        Integer workValue = 0;
        List<Integer> work_str = new ArrayList<>();
        List<SysUserWork> workList = sysUserWorkService.selectWorkyear(userAuth.getUserId());
        if (ObjectUtils.isEmpty(workList)) {
            return ResultBody.failed("信息不完整，请先完善个人工作经历");
        } else {
            for (SysUserWork work : workList) {
                work_str.add(Integer.parseInt(work.getWorkLifeleaval()));
                workValue += work.getWorkValue();
            }
        }
        if (!user.getLicenseStatus().equals("1")) {
            return ResultBody.failed("请先进行实名认证");
        }
        SysExamination examination = sysExaminationService.getById(examId);
        SysExatime sysExatime = new SysExatime();
        SysExamseason sysExamseason = new SysExamseason();
        List<EntityMap> seasonList = new ArrayList<>();
        if (ObjectUtils.isEmpty(examination)) {
            return ResultBody.failed("该考试不存在");
        } else {
            if (ObjectUtils.isNotEmpty(seasonId) && seasonId.contains(",")) {
                String[] season = seasonId.split(",");
                for (String s : season) {
                    sysExatime = sysExatimeService.getById(Long.parseLong(s));
                    if (sysExatime.getSignlastCount()-sysExatime.getSignCount()==0) {
                        return ResultBody.failed("报名场次已满");
                    }
                    sysExamseason = sysExamseasonService.getById(sysExatime.getExamseasonId());
                    if (sysExamseason.getExamTime().getTime() > DateUtils.getTimestamp()) {
                        return ResultBody.failed("该考试已超报名日期");
                    }
                    EntityMap seasonMap = new EntityMap();
                    seasonMap.put("childexamName", sysExamseason.getChildexamName());
                    seasonMap.put("examStartTime", sysExatime.getExamStartTime());
                    seasonMap.put("examEndTime", sysExatime.getExamendTime());
                    seasonMap.put("examTime", sysExatime.getExamTime());
                    seasonList.add(seasonMap);
                }
            } else {
                sysExatime = sysExatimeService.getById(Long.parseLong(seasonId));
                if (sysExatime.getSignlastCount()-sysExatime.getSignCount()==0) {
                    return ResultBody.failed("报名场次已满");
                }
                sysExamseason = sysExamseasonService.getById(sysExatime.getExamseasonId());
                if (sysExamseason.getExamTime().getTime() > DateUtils.getTimestamp()) {
                    return ResultBody.failed("该考试已超报名日期");
                }
                EntityMap seasonMap = new EntityMap();
                seasonMap.put("childexamName", sysExamseason.getChildexamName());
                seasonMap.put("examStartTime", sysExatime.getExamStartTime());
                seasonMap.put("examEndTime", sysExatime.getExamendTime());
                seasonMap.put("examTime", sysExatime.getExamTime());
                seasonList.add(seasonMap);
            }
            String examJson = examination.getExamItemJson();
            QueryWrapper<SysConditionitem> qw_s = new QueryWrapper();
            qw_s.select("id,conditionValue,conditionType,sortOrder,workValue");
            qw_s.apply("FIND_IN_SET(id,{0})", examJson.replaceAll(";", ","));
            List<SysConditionitem> its = sysConditionitemService.list(qw_s);
            List<String> stval = new ArrayList<String>();
            Map<Long, SysConditionitem> maps = its.stream().collect(Collectors.toMap(s -> s.getId(), s -> s));
            for (SysConditionitem conditionitem : its) {
                stval.add(conditionitem.getConditionValue());
            }
            //工作年限对应的code
            boolean a = false;
            Integer minEdaution = edaution_result.stream().min(Comparator.comparing(s -> s)).orElse(9999);
            String[] examIdStr = examJson.split(";");
            for (String str1 : examIdStr) {
                String[] examIdStr2 = str1.split(",");
                for (String str2 : examIdStr2) {
                    SysConditionitem conditionitem = maps.get(Long.parseLong(str2));
                    if (conditionitem == null) {
                        a = false;
                        continue;
                    }
                    if (conditionitem.getConditionType().equals(2)) {
                        if (workValue >= conditionitem.getWorkValue()) {
                            a = true;
                        } else {
                            a = false;
                            break;
                        }
                    }
                    if (conditionitem.getConditionType().equals(1)) {
                        if (conditionitem.getSortOrder() >= minEdaution) {
                            a = true;
                        } else {
                            a = false;
                            break;
                        }
                    }
                }
                if (a) {
                    break;
                }
            }

            if (a) {
                SysUserexamination userexamination = new SysUserexamination();
                userexamination.setUserId(userAuth.getUserId());
                userexamination.setExamStatus(0);
                userexamination.setExamType(0);
                userexamination.setExaminationTime(DateUtils.formatDate(sysExatime.getExamTime()));
                userexamination.setExaminationId(examination.getId());
                userexamination.setExatimeId(seasonId);
                userexamination.setExaminationHtml(examination.getExaminationHtml());
                userexamination.setExamNum(IdWorker.get32UUID());
                boolean c = sysUserexaminationService.save(userexamination);
                if(seasonId.contains(",")) {
                    String[] examStr = seasonId.split(",");
                    for (String s : examStr) {
                        SysExatime y = sysExatimeService.getById(Long.parseLong(s));
                        y.setSignlastCount(y.getSignlastCount() + 1);
                        sysExatimeService.saveOrUpdate(y);
                    }
                }else{
                    SysExatime t = sysExatimeService.getById(Long.parseLong(seasonId));
                    t.setSignlastCount(t.getSignlastCount() + 1);
                    sysExatimeService.saveOrUpdate(t);

                }
                //考试报名产生订单
                OrderInfo orderInfo = new OrderInfo();
                orderInfo.setUserId(userAuth.getUserId());
                orderInfo.setHandlerName("OT-EXAM");
                if(ObjectUtils.isNotEmpty(user.getExaminvitedId())){
                    orderInfo.setInviteId((user.getExaminvitedId()));
                }
                orderInfo.setTargetId(userexamination.getId());
                PayBeforeHandler payBeforeHandler = spring.getBean(OrderTypeEnum.getName("OT-EXAM") + "PayHandler", PayBeforeHandler.class);
                ResultBody body = payBeforeHandler.addOrder(null, orderInfo);
                log.error("111111===================================" + body.getInfo());
                if (body.isOk()) {
                    System.out.print(body);
                    log.error("111111===================================", body.getData());
                    EntityMap resultMap = new EntityMap();
                    resultMap.put("amount", examination.getAmount());
                    resultMap.put("examTime", sysExatime.getExamTime());
                    resultMap.put("exanMode", examination.getExanMode());
                    resultMap.put("examName", examination.getExamName());
                    resultMap.put("seasonList", seasonList);
                    resultMap.put("sysexamUserId", userexamination.getId());
                    resultMap.putAll((EntityMap) body.getData());
                    return ResultBody.success(resultMap);
                }
            } else {
                return ResultBody.failed("未满足报考要求，请检查个人信息");
            }
        }
        return ResultBody.success();
    }

    /**
     * 支付成功后，报名成功
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/getexamOrder")
    public ResultBody getexamOrder(String orderId) {
        CriteriaQuery<EntityMap> qw = new CriteriaQuery();
        qw.select("*");
        qw.eq("id", orderId);
        EntityMap examtype = orderService.getEntityMap(qw);
        SysUserexamination userexamination = sysUserexaminationService.getById(examtype.get("targetId"));
        SysExamination examination = sysExaminationService.getById(userexamination.getExaminationId());
        List<EntityMap> seasonList = new ArrayList<>();
        if (userexamination.getExatimeId().contains(",")) {
            String[] splt = userexamination.getExatimeId().split(",");
            for (String s : splt) {
                EntityMap seasonMap = new EntityMap();
                SysExatime sysExatime = sysExatimeService.getById(s);
                SysExamseason b = sysExamseasonService.getById(sysExatime.getExamseasonId());
                seasonMap.put("childexamName", b.getChildexamName());
                seasonMap.put("examStartTime", sysExatime.getExamStartTime());
                seasonMap.put("examEndTime", sysExatime.getExamendTime());
                seasonMap.put("examTime", sysExatime.getExamTime());
                seasonList.add(seasonMap);
            }
        } else {
            EntityMap seasonMap = new EntityMap();
            SysExatime sysExatime = sysExatimeService.getById(userexamination.getExatimeId());
            SysExamseason b = sysExamseasonService.getById(sysExatime.getExamseasonId());
            seasonMap.put("childexamName", b.getChildexamName());
            seasonMap.put("examStartTime", sysExatime.getExamStartTime());
            seasonMap.put("examEndTime", sysExatime.getExamendTime());
            seasonMap.put("examTime", sysExatime.getExamTime());
            seasonList.add(seasonMap);
        }
        EntityMap resultMap = new EntityMap();
        resultMap.put("amount", examination.getAmount());
        resultMap.put("examTime", userexamination.getExaminationTime());
        resultMap.put("exanMode", examination.getExanMode());
        resultMap.put("examName", examination.getExamName());
        resultMap.put("seasonList", seasonList);
        resultMap.put("sysexamUserId", userexamination.getId());
        resultMap.put("remark", examination.getRemark());
        return ResultBody.success(resultMap);
    }

    /**
     * 验证是否满足报考条件
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/yzexamItem")
    public ResultBody yzexamItem(String examId) {
        EntityMap map = new EntityMap();
        OpenUserAuth userAuth = OpenHelper.getUserAuth();
        CriteriaQuery<SysUser> qw = new CriteriaQuery();
        qw.eq("id", userAuth.getUserId());
        SysUser user = bizService.getOne(qw);

        if (ObjectUtils.isEmpty(user.getIdCard()) || ObjectUtils.isEmpty(user.getCardNoImg()) || ObjectUtils.isEmpty(user.getCardNoImg2())) {
            return ResultBody.failed("信息不完整，请先完善个人资料");
        }
        //教育信息是否填写
        List<Integer> edaution_result = new ArrayList<>();
        List<SysUserEduation> eduationList = sysUserEduationService.selectLeavelByUserId(userAuth.getUserId());
        if (ObjectUtils.isEmpty(eduationList)) {
            return ResultBody.failed("信息不完整，请先完善个人教育资料");
        } else {
            for (SysUserEduation eduation : eduationList) {
                edaution_result.add(Integer.parseInt(eduation.getQualifiLeavel()));
            }
        }
        //工作经历是否填写
        Integer workValue = 0;
        List<Integer> work_str = new ArrayList<>();
        List<SysUserWork> workList = sysUserWorkService.selectWorkyear(userAuth.getUserId());
        if (ObjectUtils.isEmpty(workList)) {
            return ResultBody.failed("信息不完整，请先完善个人工作经历");
        } else {
            for (SysUserWork work : workList) {
                work_str.add(Integer.parseInt(work.getWorkLifeleaval()));
                workValue += work.getWorkValue();
            }
        }
        if (!user.getLicenseStatus().equals("1")) {
            return ResultBody.failed("请先进行实名认证");
        }
        //校验用户是否参加过该考试
        EntityMap isApply = sysUserexaminationService.checkByUser(user.getId(), Long.parseLong(examId));
        if(isApply.get("isApply").equals("1")){
            if(isApply.get("addExa").equals("0")){
                return ResultBody.failed("您有该考试待支付订单", isApply.get("orderId")).setCode(105);
            }else{
                return ResultBody.failed("该考试您已报名");
            }
        }
        SysExamination examination = sysExaminationService.getById(examId);
        SysExamseason sysExamseason = new SysExamseason();
        List<EntityMap> seasonList = new ArrayList<>();
        String examJson = examination.getExamItemJson();
        QueryWrapper<SysConditionitem> qw_s = new QueryWrapper();
        qw_s.select("id,conditionValue,conditionType,sortOrder,workValue");
        qw_s.apply("FIND_IN_SET(id,{0})", examJson.replaceAll(";", ","));
        List<SysConditionitem> its = sysConditionitemService.list(qw_s);
        List<String> stval = new ArrayList<String>();
        Map<Long, SysConditionitem> maps = its.stream().collect(Collectors.toMap(s -> s.getId(), s -> s));
        for (SysConditionitem conditionitem : its) {
            stval.add(conditionitem.getConditionValue());
        }
        //工作年限对应的code
        boolean a = false;
        Integer minEdaution = edaution_result.stream().min(Comparator.comparing(s -> s)).orElse(9999);
        String[] examIdStr = examJson.split(";");
        for (String str1 : examIdStr) {
            String[] examIdStr2 = str1.split(",");
            for (String str2 : examIdStr2) {
                SysConditionitem conditionitem = maps.get(Long.parseLong(str2));
                if (conditionitem == null) {
                    a = false;
                    continue;
                }
                if (conditionitem.getConditionType().equals(2)) {
                    if (workValue >= conditionitem.getWorkValue()) {
                        a = true;
                    } else {
                        a = false;
                        break;
                    }
                }
                if (conditionitem.getConditionType().equals(1)) {
                    if (conditionitem.getSortOrder() >= minEdaution) {
                        a = true;
                    } else {
                        a = false;
                        break;
                    }
                }
            }
            if (a) {
                break;
            }
        }
        if (a) {
            return ResultBody.success("满足报考条件");
        } else {
            return ResultBody.failed("未满足报考要求，请检查个人信息");
        }
    }


    /**
     * 考试分类
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/examType")
    public ResultBody examType() {
        CriteriaQuery<SysExamtype> qw = new CriteriaQuery();
        qw.select("id,examTypeName,sortOrder");
        List<EntityMap> examtype = sysExamtypeService.listEntityMaps(qw);
        return ResultBody.success(examtype);
    }

    /**
     * 考试场次安排（小程序）
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/getexamSeason")
    public ResultBody getexamSeason(@RequestParam(value = "examId", required = false) String examId) {
        CriteriaQuery<EntityMap> qw = new CriteriaQuery();
//        qw.select("*,CONCAT(childexamName,',',DATE_FORMAT(examTime,'%Y-%m-%d')) as child_time");
        qw.select("*");
        qw.eq("examinationId", examId);
        qw.eq("status", CommonConstants.ENABLED);//查询场次开启测考试时间
        qw.orderByAsc("childexamName");
        List<EntityMap> examtype = sysExamseasonService.listEntityMaps(qw);
//         Map<String,List<EntityMap>> map=examtype.stream().collect(Collectors.groupingBy(e->e.get("child_time")));
        List<EntityMap> returnList = new ArrayList<>();
        for (EntityMap map2 : examtype) {
            CriteriaQuery<EntityMap> qw_1 = new CriteriaQuery();
            qw_1.select("*");
            qw_1.eq("examseasonId", map2.get("id"));
            List<EntityMap> sliList = sysExatimeService.listEntityMaps(qw_1);
            Map<String, List<EntityMap>> resultmap = sliList.stream().collect(Collectors.groupingBy(e -> e.get("examTime")));
            List<EntityMap> list = new ArrayList<>();
            for (String time : resultmap.keySet()) {
                EntityMap entityMap = new EntityMap();
                entityMap.put("time", time);
                entityMap.put("timeList", resultmap.get(time));
                list.add(entityMap);
            }
            map2.put("sliList", list);
            returnList.add(map2);
        }
        return ResultBody.success(returnList);
    }


    /**
     * 考试安排
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/examTypelist")
    public ResultBody examTypelist(@RequestParam(value = "examTypeId", required = false) String examTypeId) {
        CriteriaQuery<SysExamination> qw = new CriteriaQuery();
        qw.select("e.id as examId,e.examName,e.applyBeginDate,e.applyEndDate,e.examEndTime,e.exanMode,e.payEndDate,e.quitDate,e.examinationHtml,e.examItemJson,e.remark,sysexamType.id as examTypeId,sysexamType.examTypeName");
        if (ObjectUtils.isNotEmpty(examTypeId)) {
            qw.eq("e.examTypeId", examTypeId);
        }
        //新增开启状态
        qw.eq("isOpen", CommonConstants.ENABLED);
        qw.eq("isDel", 0);//状态为未删除的
        qw.orderByDesc("e.createTime");
        qw.eq("examType", "0");//证书报考

        qw.createAlias("sysexamType", "sysexamType");
        List<EntityMap> userCertificateList = sysExaminationService.listEntityMaps(qw);
        List<EntityMap> resultMap = new ArrayList<>();
        for (EntityMap result : userCertificateList) {
            String examItemJson = result.get("examItemJson");
            Map<Long, String> itemMap = sysConditionitemService.selectItems();
            String[] items = examItemJson.split(";");
            String itemName = "";
            for (String it : items) {
                String[] typeList = it.split(",");
                for (String type : typeList) {
                    itemName += itemMap.get(Long.valueOf(type));
                }
                itemName += "/";
            }
            itemName = itemName.substring(0, itemName.length() - 1);
            result.put("conditionitem", itemName);
            resultMap.add(result);
        }
        return ResultBody.success(resultMap);
    }

    /**
     * 考试安排(证书认定考试)
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/getexamType")
    public ResultBody getexamType(@RequestParam(value = "examTypeId", required = false) String syscertificateId) {
        CriteriaQuery<SysExamination> qw = new CriteriaQuery();
        qw.select("e.id as examId,e.examName,e.applyBeginDate,e.applyEndDate,e.examEndTime,e.exanMode,e.payEndDate,e.quitDate,e.examinationHtml,e.examItemJson,e.remark,sysexamType.id as examTypeId,sysexamType.examTypeName");
        //新增开启状态
        qw.eq("certificateId",syscertificateId);
        qw.eq("isOpen", CommonConstants.ENABLED);
        qw.eq("isDel", 0);//状态为未删除的
        qw.eq("examType", "1");//证书认定
        qw.orderByDesc("e.createTime");
        qw.createAlias("sysexamType", "sysexamType");
        List<EntityMap> userCertificateList = sysExaminationService.listEntityMaps(qw);
        return ResultBody.success(userCertificateList);
    }

    /**
     * 考试报名（验证报考条件）
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/addexam")
    public ResultBody addexam(@RequestParam(value = "examId", required = false) String examId, @RequestParam(value = "seasonId", required = false) String seasonId,Long usercertificateId) {
        EntityMap map = new EntityMap();
        OpenUserAuth userAuth = OpenHelper.getUserAuth();
        CriteriaQuery<SysUser> qw = new CriteriaQuery();
        qw.eq("id", userAuth.getUserId());
        SysUser user = bizService.getOne(qw);

        //校验用户是否参加过该考试时
        EntityMap isApply = sysUserexaminationService.checkByUsercert(user.getId(), Long.parseLong(examId),usercertificateId);
        if(isApply.get("isApply").equals("1")){
            if(isApply.get("addExa").equals("0")){
                return ResultBody.failed("您有该考试待支付订单", isApply.get("orderId")).setCode(105);
            }else{
                return ResultBody.failed("该考试您已报名");
            }
        }
//        if (ObjectUtils.isEmpty(user.getIdCard()) || ObjectUtils.isEmpty(user.getCardNoImg()) || ObjectUtils.isEmpty(user.getCardNoImg2())) {
//            return ResultBody.failed("信息不完整，请先完善个人资料");
//        }
//        //教育信息是否填写
//        List<Integer> edaution_result = new ArrayList<>();
//        List<SysUserEduation> eduationList = sysUserEduationService.selectLeavelByUserId(userAuth.getUserId());
//        if (ObjectUtils.isEmpty(eduationList)) {
//            return ResultBody.failed("信息不完整，请先完善个人教育资料");
//        } else {
//            for (SysUserEduation eduation : eduationList) {
//                edaution_result.add(Integer.parseInt(eduation.getQualifiLeavel()));
//            }
//        }
//        //工作经历是否填写
//        Integer workValue = 0;
//        List<Integer> work_str = new ArrayList<>();
//        List<SysUserWork> workList = sysUserWorkService.selectWorkyear(userAuth.getUserId());
//        if (ObjectUtils.isEmpty(workList)) {
//            return ResultBody.failed("信息不完整，请先完善个人工作经历");
//        } else {
//            for (SysUserWork work : workList) {
//                work_str.add(Integer.parseInt(work.getWorkLifeleaval()));
//                workValue += work.getWorkValue();
//            }
//        }
//        if (!user.getLicenseStatus().equals("1")) {
//            return ResultBody.failed("请先进行实名认证");
//        }
        SysExamination examination = sysExaminationService.getById(examId);
        SysExatime sysExatime = new SysExatime();
        SysExamseason sysExamseason = new SysExamseason();
        List<EntityMap> seasonList = new ArrayList<>();
        if (ObjectUtils.isEmpty(examination)) {
            return ResultBody.failed("该考试不存在");
        } else {
            if (ObjectUtils.isNotEmpty(seasonId) && seasonId.contains(",")) {
                String[] season = seasonId.split(",");
                for (String s : season) {
                    sysExatime = sysExatimeService.getById(Long.parseLong(s));
                    if (sysExatime.getSignlastCount()-sysExatime.getSignCount()==0) {
                        return ResultBody.failed("报名场次已满");
                    }
                    sysExamseason = sysExamseasonService.getById(sysExatime.getExamseasonId());
                    if (sysExamseason.getExamTime().getTime() > DateUtils.getTimestamp()) {
                        return ResultBody.failed("该考试已超报名日期");
                    }
                    EntityMap seasonMap = new EntityMap();
                    seasonMap.put("childexamName", sysExamseason.getChildexamName());
                    seasonMap.put("examStartTime", sysExatime.getExamStartTime());
                    seasonMap.put("examEndTime", sysExatime.getExamendTime());
                    seasonMap.put("examTime", sysExatime.getExamTime());
                    seasonList.add(seasonMap);
                }
            } else {
                sysExatime = sysExatimeService.getById(Long.parseLong(seasonId));
                if (sysExatime.getSignlastCount()-sysExatime.getSignCount()==0) {
                    return ResultBody.failed("报名场次已满");
                }
                sysExamseason = sysExamseasonService.getById(sysExatime.getExamseasonId());
                if (sysExamseason.getExamTime().getTime() > DateUtils.getTimestamp()) {
                    return ResultBody.failed("该考试已超报名日期");
                }
                EntityMap seasonMap = new EntityMap();
                seasonMap.put("childexamName", sysExamseason.getChildexamName());
                seasonMap.put("examStartTime", sysExatime.getExamStartTime());
                seasonMap.put("examEndTime", sysExatime.getExamendTime());
                seasonMap.put("examTime", sysExatime.getExamTime());
                seasonList.add(seasonMap);
            }
                SysUserexamination userexamination = new SysUserexamination();
                userexamination.setUserId(userAuth.getUserId());
                userexamination.setExamStatus(0);
                userexamination.setExamType(0);
                userexamination.setUsercertificateId(usercertificateId);
                userexamination.setExaminationTime(DateUtils.formatDate(sysExatime.getExamTime()));
                userexamination.setExaminationId(examination.getId());
                userexamination.setExatimeId(seasonId);
                userexamination.setExaminationHtml(examination.getExaminationHtml());
                userexamination.setExamNum(IdWorker.get32UUID());
                boolean c = sysUserexaminationService.save(userexamination);
                if(seasonId.contains(",")) {
                    String[] examStr = seasonId.split(",");
                    for (String s : examStr) {
                        SysExatime y = sysExatimeService.getById(Long.parseLong(s));
                        y.setSignlastCount(y.getSignlastCount() + 1);
                        sysExatimeService.saveOrUpdate(y);
                    }
                }else{
                    SysExatime t = sysExatimeService.getById(Long.parseLong(seasonId));
                    t.setSignlastCount(t.getSignlastCount() + 1);
                    sysExatimeService.saveOrUpdate(t);
                }
                //考试报名产生订单
                OrderInfo orderInfo = new OrderInfo();
                orderInfo.setUserId(userAuth.getUserId());
                orderInfo.setHandlerName("OT-EXAM");
                orderInfo.setTargetId(userexamination.getId());
                PayBeforeHandler payBeforeHandler = spring.getBean(OrderTypeEnum.getName("OT-EXAM") + "PayHandler", PayBeforeHandler.class);
                ResultBody body = payBeforeHandler.addOrder(null, orderInfo);
                log.error("111111===================================" + body.getInfo());
                if (body.isOk()) {
                    System.out.print(body);
                    log.error("111111===================================", body.getData());
                    EntityMap resultMap = new EntityMap();
                    resultMap.put("amount", examination.getAmount());
                    resultMap.put("examTime", sysExatime.getExamTime());
                    resultMap.put("exanMode", examination.getExanMode());
                    resultMap.put("examName", examination.getExamName());
                    resultMap.put("seasonList", seasonList);
                    resultMap.put("sysexamUserId", userexamination.getId());
                    resultMap.putAll((EntityMap) body.getData());
                    return ResultBody.success(resultMap);
                }
            }
        return ResultBody.success();
    }

    /**
     * 我的证书、证书查询
     */
    @RequestMapping(value = "/myCertificate")
    public ResultBody mycertificate(String idCard) {
        EntityMap entityMap = new EntityMap();
        OpenUserAuth userAuth = OpenHelper.getUserAuth();
        if (ObjectUtils.isEmpty(userAuth.getUserId())) {
            return ResultBody.failed("请重新登录");
        }
        SysUser user = bizService.getById(userAuth.getUserId());
        if (ObjectUtils.isEmpty(user.getIdCard())) {
            return ResultBody.failed("该账户还未完成实名认证");
        }
        QueryWrapper<SysUsercertificate> qw = new QueryWrapper();
        qw.eq("userId", userAuth.getUserId());
        qw.eq("idCard", idCard);
        qw.orderByDesc("createTime");
        List<SysUsercertificate> userCertificateList = sysUsercertificateService.list(qw);
        entityMap.put("userCertificateList", userCertificateList);
        ResultBody resultBody = new ResultBody();
        resultBody.setData(entityMap);
        resultBody.setInfo("操作成功");
        return resultBody;
    }


    /**
     * 证书初始化页面
     */
    @RequestMapping(value = "/userzsList")
    public ResultBody userzsList() {
        OpenUserAuth userAuth = OpenHelper.getUserAuth();
        EntityMap returnMap = new EntityMap();
        CriteriaQuery<SysCertificate> certificate = new CriteriaQuery<>();
        certificate.select("id,certificateName,certificateCode");
        certificate.eq("applyType", 1);
        List<EntityMap> certificateList = sysCertificateService.listEntityMaps(certificate);
        CriteriaQuery<SysUsercertificate> qw = new CriteriaQuery();
        qw.select("*,certificate.certificateName,IF((certificate.isStudy = 1 OR certificate.isChange = 1), 1, 0) del");
        qw.eq("userId", userAuth.getUserId());
        qw.createAlias("certificate", "certificate");
        List<EntityMap> userctList = sysUsercertificateService.listEntityMaps(qw);
        returnMap.put("certificateType", certificateList);
        returnMap.put("userctList", userctList);
        return ResultBody.success(returnMap);
    }

    /**
     * 添加证书
     */
    @RequestMapping(value = "/addusercertificate")
    public ResultBody addusercertificate(SysUsercertificate sysUsercertificate) {
       List<EntityMap> certist= sysUsercertificateService.ifexists(sysUsercertificate.getCertificateId());
       if(certist.size()>0){
           for(EntityMap entityMap:certist){
               String time=entityMap.get("validity");
               Date timetimp = DateUtil.parse(time,"yyyy-MM-dd");
               long currentTime = System.currentTimeMillis();
               if(timetimp.getTime()>currentTime){
                   return ResultBody.failed("请勿重复提交同种类型证书");
               }
           }
       }
        OpenUserAuth userAuth = OpenHelper.getUserAuth();
        sysUsercertificate.setUserId(userAuth.getUserId());
        if(ObjectUtils.isNotEmpty(sysUsercertificate.getCertificateId())){
            SysCertificate certificate=sysCertificateService.getById(sysUsercertificate.getCertificateId());
            //是转换学分证书可直接
            if(certificate.getIsChange().equals(1)&&certificate.getIsConvert().equals(0)){
                sysUsercertificate.setChangeStatus(0);//可申请转换证明的
            }
        }
        boolean a = sysUsercertificateService.saveOrUpdate(sysUsercertificate);
        if (a) {
            return ResultBody.success(sysUsercertificate);
        }
        return ResultBody.failed("提交失败");
    }

    /**
     * 删除证书
     */
    @RequestMapping(value = "/delcertificate")
    public ResultBody delcertificate(Long certificateId) {
        OpenUserAuth userAuth = OpenHelper.getUserAuth();
        SysUsercertificate sysUsercertificate = sysUsercertificateService.getById(certificateId);
        if (ObjectUtils.isEmpty(sysUsercertificate)) {
            return ResultBody.failed("证书不存在");
        }
        boolean a = sysUsercertificateService.removeById(certificateId);
        if (a) {
            return ResultBody.success("删除成功");
        }
        return ResultBody.failed("删除失败");
    }

    /**
     * 分享用户信息(产品、报考)
     */
    @RequestMapping(value = "/shareUsermsg")
    public ResultBody shareUsermsg(String url) {
        OpenUserAuth userAuth = OpenHelper.getUserAuth();
        SysUser uer=bizService.getById(userAuth.getUserId());
        File logoFile=new File("c:/qbjy/logo.png");
        if(ObjectUtils.isNotEmpty(uer.getAvatar())){
            HttpUtil.downloadFile(uer.getAvatar(),logoFile);
        }
        Map< EncodeHintType, ?> hint=new HashMap();
        BufferedImage image = QRCodeUtils.createQRCodeWithLogo(url,"UTF-8",hint,250,250,logoFile);// 生成图片 不需要的话注释即可
        String baseurl = QRCodeUtils.getImageBase64String(image);
        return ResultBody.success(baseurl);
    }

    /**
     * 分享更新绑定关系(产品、报考)
     */
    @RequestMapping(value = "/bindshareMsg")
    public ResultBody bindshareMsg(Long invitedId,String inviteType) {
        OpenUserAuth userAuth = OpenHelper.getUserAuth();
        SysUser user=bizService.getById(userAuth.getUserId());
        if(ObjectUtils.isNotEmpty(user)){
            if(ObjectUtils.isNotEmpty(inviteType)&&ObjectUtils.isNotEmpty(invitedId)){
                if(inviteType.equals("1")){//考试推荐类型
                    user.setExaminvitedId(invitedId);
                }
                if(inviteType.equals("2")){//会员购买类型
                    user.setVipinvitedId(invitedId);
                }
                if(inviteType.equals("3")){//课程购买类型
                    user.setCourseinvitedId(invitedId);
                }
            }
            bizService.saveOrUpdate(user);
        }
        return  ResultBody.success(user);
    }
    /**
     * 申请注册国开学籍号
     */
    @RequestMapping(value = "/applygkNum")
    public ResultBody applygkNum() {
        OpenUserAuth userAuth = OpenHelper.getUserAuth();
        SysUser sysUser=bizService.getById(userAuth.getUserId());
        if(ObjectUtils.isEmpty(sysUser)){
          return  ResultBody.failed("用户不存在");
        }else{
            if(ObjectUtils.isEmpty(sysUser.getIdCard())){
                return  ResultBody.failed("请完善个人身份认证信息");
            }else{
                sysUser.setSchoolRegister("1");
                boolean a=bizService.saveOrUpdate(sysUser);
            }
        }
        return ResultBody.success(sysUser);
    }
    /**
     * 申请注册国开学籍号
     */
    @RequestMapping(value = "/getImage")
    public ResultBody getImage() {
        CriteriaQuery<EntityMap> qw = new CriteriaQuery();
        qw.select("*");
        qw.in("configName", "xcxHeard","xcxRight","xcxLeft");
        List<EntityMap> imageList = sysConfigService.listEntityMaps(qw);
        return ResultBody.success(imageList);
    }

}
